import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  Picker,
  Image,
  TouchableOpacity
} from 'react-native'

import { connect } from 'react-redux'
import HeaderDefault from '../../components/header/HeaderDefault'
import { theme_app, theme_text } from '../../utils/appTheme'
import Modal from '../../components/ModalBox'
import { addFallAssess, getFallAssessListByPno } from '../../netServer/eve'

import Toast from 'react-native-simple-toast'
import { isNotEmptyArray } from '../../utils/structureJudgment'

class EveTumbleDetail extends Component {
  constructor(props) {
    super(props)

    //     case 0:
    //     return ['有(25)', '无(0)']

    //   case 1:
    //     return ['有(15)', '无(0)']

    //   case 2:
    //     return [
    //       ,
    //       '使用拐杖、手杖、助行器(15)',
    //       '扶靠家具行走(30)'
    //     ]

    //   case 3:
    //     return ['有(20)', ]

    //   case 4:
    //     return [
    //       ,
    //       '双下肢乏力(10)',
    //       '残疾或功能障碍(20)'
    //     ]

    //   case 5:
    //     return [, '认知障碍(15)']

    //   default:
    //     break
    // }

    this.state = {
      currentModalStatus: 0,
      fall_history: '无(0)', //跌倒史
      diagnose: '无(0)', //超过一个医学诊断
      walk: '卧床休息，有他人照顾活动或不需要使用(0)', //行走辅助
      vein: '无(0)', //静脉输液治疗
      gait: '正常、卧床休息不能活动(0)', //步态
      cognize: '正常，能量力而行(0)', //认知状态
      score: 0, //总分
      risk: '低危' //风险等级
    }
  }
  static navigationOptions = ({ navigation }) => ({
    header: (
      <HeaderDefault
        rightRitle="提交"
        rihghtBtnOnPress={() => {
          navigation.state.params.clickRightMethod()
        }}
        backBtnOnPress={navigation.goBack}
        title="跌倒、坠床评估"
      />
    )
  })

  componentDidMount() {
    this.props.navigation.setParams({ clickRightMethod: this._ritBtn })
    this._getFallAssessListByPno()
  }

  _getFallAssessListByPno = () => {
    let params = new FormData()
    let { patient_no } = this.props.navigation.state.params.pinfo
    params.append('patientNo', patient_no)
    getFallAssessListByPno(params, resp => {
      let { code, data = [], msg } = resp
      if (code == '0') {
        this._firstInitState(data)
      } else {
        Toast.showWithGravity(msg, Toast.LONG, Toast.CENTER)
      }
    })
  }

  _firstInitState = data => {
    if (isNotEmptyArray(data)) {
      let newData = data[0]

      let { fall_history, diagnose, walk, vein, gait, cognize, score } = newData

      this.setState({
        fall_history: fall_history === 'null' ? null : fall_history,
        diagnose: diagnose === 'null' ? null : diagnose,
        walk: walk === 'null' ? null : walk,
        vein: vein === 'null' ? null : vein,
        gait: gait === 'null' ? null : gait,
        cognize: cognize === 'null' ? null : cognize,
        score: score
      })
    }
  }

  _ritBtn = () => {
    let params = new FormData()
    let { patient_no } = this.props.navigation.state.params.pinfo
    params.append('patient_no', patient_no)
    params.append('fall_history', this.state.fall_history)
    params.append('diagnose', this.state.diagnose)
    params.append('walk', this.state.walk)
    params.append('vein', this.state.vein)
    params.append('gait', this.state.gait)
    params.append('cognize', this.state.cognize)
    params.append('score', this.state.score)

    let riskStr = ''
    if (this.state.score < 25) {
      riskStr = '低危'
    } else if (this.state.score < 46) {
      riskStr = '中危'
    } else {
      riskStr = '高危'
    }

    params.append('risk', riskStr)
    let { user_id } = this.props.user_info
    params.append('create_by', user_id)

    addFallAssess(params, resp => {
      let { code, data = [], msg } = resp

      if (code == '0') {
        Toast.showWithGravity('提交成功', Toast.LONG, Toast.CENTER)
      } else {
        Toast.showWithGravity(msg, Toast.LONG, Toast.CENTER)
      }
    })
  }

  _renderItem = item => {
    let {
      name,
      bed_no,
      sex,
      age,
      allergy,
      gradeName,
      inhosp_no,
      days,
      charge_type
    } = item
    return (
      <View
        style={{
          width: screenWidth,
          height: 100,
          borderBottomColor: '#efefef',
          borderBottomWidth: 1,
          backgroundColor: 'white'
        }}
      >
        <View
          style={{
            width: screenWidth,
            height: 40,
            paddingLeft: 16,
            paddingRight: 16,
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'space-between'
          }}
        >
          <Text style={{ fontSize: 16 }}>{name}</Text>
          <Text>{bed_no}</Text>
        </View>

        <View
          style={{
            width: screenWidth,
            height: 30,
            paddingLeft: 16,
            paddingRight: 16,
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'space-between'
          }}
        >
          <Text>
            {sex == 1 ? '男' : '女'}/{age}
          </Text>
          <Text>{inhosp_no}</Text>
          <Text>{days}</Text>
          <Text>{charge_type}</Text>
        </View>

        <View
          style={{
            width: screenWidth,
            height: 30,
            paddingLeft: 16,
            paddingRight: 16,
            alignItems: 'center',
            flexDirection: 'row'
          }}
        >
          <Text style={{ width: 80, color: 'green' }}>{gradeName}</Text>
          <Text style={{ color: 'red' }}>{allergy}</Text>
        </View>
      </View>
    )
  }

  _getModalDataSource(Currentstatus) {
    switch (Currentstatus) {
      case 0:
        return ['有(25)', '无(0)']

      case 1:
        return ['有(15)', '无(0)']

      case 2:
        return [
          '卧床休息，有他人照顾活动或不需要使用(0)',
          '使用拐杖、手杖、助行器(15)',
          '扶靠家具行走(30)'
        ]

      case 3:
        return ['有(20)', '无(0)']

      case 4:
        return [
          '正常、卧床休息不能活动(0)',
          '双下肢乏力(10)',
          '残疾或功能障碍(20)'
        ]

      case 5:
        return ['正常，能量力而行(0)', '认知障碍(15)']

      default:
        break
    }
  }

  _getModaldefaultVaule(Currentstatus) {
    switch (Currentstatus) {
      case 0:
        return this.state.fall_history
        break

      case 1:
        return this.state.diagnose
        break
      case 2:
        return this.state.walk
        break
      case 3:
        return this.state.vein
        break
      case 4:
        return this.state.gait
        break
      case 5:
        return this.state.cognize
        break
      default:
        break
    }
  }

  _calculateScore = () => {
    setTimeout(this._calculateScoreAfter, 300)
  }

  _calculateScoreAfter = () => {
    let newScore = 0

    if (this.state.fall_history === '有(25)') {
      newScore = newScore + 25
    }

    if (this.state.diagnose === '有(15)') {
      newScore = newScore + 15
    }

    if (this.state.walk === '使用拐杖、手杖、助行器(15)') {
      newScore = newScore + 15
    }
    if (this.state.walk === '扶靠家具行走(30)') {
      newScore = newScore + 30
    }
    if (this.state.vein === '有(20)') {
      newScore = newScore + 20
    }

    if (this.state.gait === '双下肢乏力(10)') {
      newScore = newScore + 10
    }

    if (this.state.gait === '残疾或功能障碍(20)') {
      newScore = newScore + 20
    }
    if (this.state.cognize === '认知障碍(15)') {
      newScore = newScore + 15
    }

    this.setState({ score: newScore })
  }

  _modalSetValue = value => {
    switch (this.state.currentModalStatus) {
      case 0:
        this.setState({ fall_history: value }, this._calculateScore())
        break

      case 1:
        this.setState({ diagnose: value }, this._calculateScore())
        break
      case 2:
        this.setState({ walk: value }, this._calculateScore())
        break
      case 3:
        this.setState({ vein: value }, this._calculateScore())
        break
      case 4:
        this.setState({ gait: value }, this._calculateScore())
        break
      case 5:
        this.setState({ cognize: value }, this._calculateScore())
        break
      default:
        break
    }
  }

  _renderModalBox = () => {
    let dataSoure = this._getModalDataSource(this.state.currentModalStatus)

    let set_vale = this._getModaldefaultVaule(this.state.currentModalStatus)
    return (
      <Modal
        style={styles.modal3}
        position={'bottom'}
        backdropPressToClose={false}
        swipeToClose={false}
        ref={md => (this.myModel = md)}
      >
        <View style={{ flex: 1 }}>
          <View
            style={{
              width: screenWidth,
              height: 50,
              flexDirection: 'row-reverse',
              alignItems: 'center'
            }}
          >
            <TouchableOpacity
              onPress={() => {
                this.myModel.close()
              }}
              style={{
                width: 50,
                height: 50,
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Image
                style={{ width: 30, height: 30 }}
                source={require('./src/guanbi.png')}
              />
            </TouchableOpacity>
          </View>

          <Picker
            selectedValue={set_vale}
            style={{
              height: 50,
              width: screenWidth
            }}
            onValueChange={this._modalSetValue}
          >
            {dataSoure.map((value, index) => {
              return (
                <Picker.Item key={value + index} label={value} value={value} />
              )
            })}
          </Picker>
          <View style={{ width: screenWidth, height: 30 }} />
        </View>
      </Modal>
    )
  }

  render() {
    let isDangerColor = this.state.score > 24 ? 'red' : '#222'
    return (
      <View style={styles.container}>
        {this._renderItem(this.props.navigation.state.params.pinfo)}
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>跌倒史</Text>
          </View>
          <TouchableOpacity
            onPress={() => {
              this.setState(
                {
                  currentModalStatus: 0
                },
                this.myModel.open()
              )
            }}
            style={styles.sectionRight}
          >
            <Text>{this.state.fall_history}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>超过1个医学诊断</Text>
          </View>

          <TouchableOpacity
            onPress={() => {
              this.setState(
                {
                  currentModalStatus: 1
                },
                this.myModel.open()
              )
            }}
            style={styles.sectionRight}
          >
            <Text>{this.state.diagnose}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>行走辅助</Text>
          </View>

          <TouchableOpacity
            onPress={() => {
              this.setState(
                {
                  currentModalStatus: 2
                },
                this.myModel.open()
              )
            }}
            style={styles.sectionRight}
          >
            <Text>{this.state.walk}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>静脉输液治疗</Text>
          </View>
          <TouchableOpacity
            onPress={() => {
              this.setState(
                {
                  currentModalStatus: 3
                },
                this.myModel.open()
              )
            }}
            style={styles.sectionRight}
          >
            <Text>{this.state.vein}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>步态</Text>
          </View>
          <TouchableOpacity
            onPress={() => {
              this.setState(
                {
                  currentModalStatus: 4
                },
                this.myModel.open()
              )
            }}
            style={styles.sectionRight}
          >
            <Text>{this.state.gait}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>认知状态</Text>
          </View>
          <TouchableOpacity
            onPress={() => {
              this.setState(
                {
                  currentModalStatus: 5
                },
                this.myModel.open()
              )
            }}
            style={styles.sectionRight}
          >
            <Text>{this.state.cognize}</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.sectionS}>
          <View style={styles.sectionLeft}>
            <Text>总分</Text>
          </View>
          <View style={styles.sectionRight}>
            <Text style={{ color: isDangerColor }}>{this.state.score}</Text>
          </View>
        </View>

        <View style={[styles.sectionLeft, { width: screenWidth }]}>
          <Text style={{ color: '#aa0000', fontSize: 16 }}>
            低危:分值0~24分;中危:分值25~45分;高危:分值> 45分;
          </Text>
        </View>

        {this._renderModalBox()}
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme_app.bg_color
  },
  sectionS: {
    width: screenWidth,
    height: 50,
    flexDirection: 'row',
    borderBottomColor: '#efefef',
    borderBottomWidth: 1,
    backgroundColor: 'white'
  },
  sectionLeft: {
    width: 0.4 * screenWidth,
    height: 50,
    justifyContent: 'center',
    paddingLeft: 10,
    borderRightColor: '#efefef',
    borderRightWidth: 1
  },
  modal3: {
    height: 250,
    width: screenWidth
    // justifyContent: 'center',
    // alignItems: 'center'
  },
  sectionRight: {
    width: 0.6 * screenWidth,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

function select(store) {
  return { user_info: store.userInfo.user_info }
}

export default connect(select)(EveTumbleDetail)
